<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input
        v-model="searchParam.SEARCH_LIKE_name"
        placeholder="请输入关键字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      > 新增
      </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :align="column.align?column.align:'center'"
        :min-width="column.minWidth"
        :sortable="column.sortable"
        :fixed="column.fixed"
        :type="column.type"
        :formatter="column.formatter"
      >
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img
            v-if="column.imgFlag==true"
            :src=" scope.row[column.prop].indexOf('http://') >-1 ? scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
            width="60"
            height="60"
            class="img"
          >
          <!-- 行内显示开关按钮 -->
          <el-switch
            v-else-if="column.switchFlag==true"
            v-model="scope.row[column.prop]"
            :active-value="1"
            :inactive-value="0"
            disabled
          />
          <!-- 行内显示tag标签 -->
          <span v-else-if="column.tagFlag==true">
            <span v-for="item in column.tagFormatter" :key="item.value">
              <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
            </span>
          </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
          <!--默认显示文本-->
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"> 编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination
      v-show="tableTotal>0"
      :total="tableTotal"
      :page.sync="pageRequest.pageNum"
      :limit.sync="pageRequest.pageSize"
      @pagination="getList"
    />

    <!--新增编辑界面-->
    <el-dialog
      :title="operation?'新增':'编辑'"
      width="45%"
      top="5vh"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form ref="dataForm" :model="dataForm" label-width="140px" :rules="dataFormRules" style="width: 80%">

        <el-form-item label="登录名" prop="username">
          <el-input v-model="dataForm.username" auto-complete="off" placeholder="请输入登录名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="dataForm.realname" auto-complete="off" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="用户头像" prop="avatar">
          <Upload v-model="dataForm.avatar" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="dataForm.phone" auto-complete="off" placeholder="请输入电话号码" />
        </el-form-item>
<!--        <el-form-item label="地区" prop="provinceCode">-->
<!--          <area-cascade v-model="areaCasResult" />-->
<!--        </el-form-item>-->
        <!--        <el-form-item label="电子邮箱" prop="email">-->
        <!--          <el-input v-model="dataForm.email" auto-complete="off" placeholder="请输入电子邮箱" />-->
        <!--        </el-form-item>-->
        <el-form-item label="用户角色" prop="roles">
          <el-select v-model="dataForm.roles" clearable placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
          <el-form-item label="状态" prop="state">
              <el-switch v-model="dataForm.state" :active-value="1"
                         :inactive-value="0"></el-switch>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" :loading="editLoading" type="primary" @click.native="saveFormData()">提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import { getUserList, saveUserInfo, deleteUser, getRoleList, getRolesIdByUid } from '@/api/modules/cm-system'
import Upload from '@/components/Upload' // 上传图片组件引入
import AreaCascade from '@/components/AreaCascade'

export default {
  name: '',
  components: {
    Pagination,
    Upload,
    AreaCascade
  },
  directives: {},
  filters: {},
  data() {
    return {
      tableKey: 0,
      tableList: [], // 表格数据源
      tableTotal: 0, // 表格总条数数据
      listLoading: true,
      pageRequest: { pageNum: 1, pageSize: 10 },
      searchParam: { SEARCH_LIKE_name: '' },
      dialogFormVisible: false, // 默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false, // 保存表单时loading框
      columns: [
        { prop: 'username', label: '登录名', sortable: false },
        { prop: 'realname', label: '真实姓名', sortable: false },
        { prop: 'avatar', label: '用户头像', sortable: false, imgFlag: true },
        { prop: 'phone', label: '电话号码', sortable: false },
        { prop: 'state', label: '用户状态', sortable: false ,switchFlag: true },
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      options: [],
      areaCasResult: {
        provinceCode: '',
        cityCode: '',
        countryCode: '',
        address: ''
      },
      // 表单检验规则
      dataFormRules: {
        username: [{ required: true, message: '请输入登录名', trigger: 'blur' }],
        realname: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
        avatar: [{ required: true, message: '请输入用户头像', trigger: 'blur' }],
          roles: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
      }
    }
  },
  watch: {
    // 省、市、区数据回显
    areaCasResult: {
      immediate: true,
      handler(val) {
        this.dataForm.provinceCode = val.provinceCode
        this.dataForm.cityCode = val.cityCode
        this.dataForm.countryCode = val.countryCode
        this.dataForm.address = val.address
      }
    }
  },
  mounted: function() {
    this.getRoleList()
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取表格数据
    getList() {
      this.listLoading = true
      // 【API请求】----获取表格列表数据
      getUserList(this.pageRequest).then(response => {
          this.tableList = response.result.content
          this.tableTotal = response.result.total
          this.listLoading = false
      }).catch((res) => {
        this.$message({ message: '列表获取失败', type: 'error' })
      })
    },
    getRoleList() {
      this.listLoading = true
      // 【API请求】----获取表格列表数据
      getRoleList(this.pageRequest).then(response => {
          this.options = response.result.content
          // console.log(this.options)
          this.listLoading = false
      }).catch((res) => {
        this.$message({ message: '角色列表获取失败', type: 'error' })
      })
    },
    // 表格数据筛选
    handleFilter() {
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    // 【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true
      this.initDataForm()
      this.areaCasResult = {}
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
      })
    },
    // 【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false
      const { provinceCode, cityCode, countryCode } = row
      this.areaCasResult = { provinceCode, cityCode, countryCode }
      row.roles = '',
      this.dataForm = Object.assign({}, row)
      // 【API请求】----根据用户id 获取关联的角色ids
      getRolesIdByUid({ id: row.id }).then(response => {
        this.dataForm.roles = response.result.role
      })
      // 显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false
      })
    },
    // 保存表单数据
    saveFormData() {
      let res
      this.$refs['dataForm'].validate(async(valid) => {
        if (!valid) {
          return false
        }
        this.editLoading = true
        // 【API请求】----保存数据
        res = await saveUserInfo(this.dataForm)
        try {
          if (res.code === 0) {
            this.dialogFormVisible = false// 关闭表单页面
            this.initDataForm()// 重置表单数据
            this.getList()// 重新获取表格数据
            this.$notify({ title: '成功', message: '保存成功', type: 'success', duration: 2000 })
          }
          this.editLoading = false// 关闭loading框
        } catch (e) {
          throw e
        }
      })
    },
    // 【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        // 【API请求】---- 删除数据
        deleteUser({ ids: row.id }).then(() => {
          this.$message({ message: '操作成功', type: 'success' })
          this.getList()
        })
      }).catch(() => {
        this.$message({ message: '操作失败', type: 'error' })
      })
    },
    // 初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        id: '',
        username: '',
        realname: '',
        password: '',
        salt: '',
        phone: '',
        email: '',
        avatar: '',
        state: '',
        remark: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: ''
      }
    },
    // 关闭表单弹出框
    closeDialog() {
      this.$refs['dataForm'].resetFields()
      this.dialogFormVisible = false
    }
  }
}
</script>
